//app.js

var util = require('utils/util.js');

App({
  
  onLaunch: function() {
    var that = this;
    //update the new version
    that.getNewVersion();
    //调用API从本地缓存中获取数据
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs);

    //get the identifier
    that.globalData.identifier = wx.getStorageSync("telephone");
    that.globalData.userSig = wx.getStorageSync("userSig");

    that.globalData.companyName = wx.getStorageSync("companyName");
    that.globalData.FaceUrl = wx.getStorageSync("FaceUrl");
    console.log("the identifier is " + that.globalData.identifier);
    console.log("the userSig is " + that.globalData.userSig);
    wx.login({
      success: function(res) {
        if (res.code) {
          console.log("login success");
          console.log("get the js_code successfully,it's value is " + res.code);
          that.globalData.js_code = res.code;
          console.log("that.globalData.js_code is " + that.globalData.js_code);

          // 通过js_code发送request获取session_key和openid
          getSessionkeyAndOpenId(that);

          //getAccessToken
          getAccessToken(that);

          
          
          
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    });
    // end login

    setInterval(that.refreshjs_code, 1000 * 250);
    //get the AccessToken every 7000 seconds
    setInterval(that.refreshSessionkeyAndOpenId, 1000 * 7000);
    setInterval(that.refreshAccessToken, 1000 * 7000);


    wx.getSystemInfo({
      success: res => {
        //导航高度
        this.globalData.navHeight = res.statusBarHeight + 46;
      }, fail(err) {
        console.log(err);
      }
    })


    wx.getSystemInfo({
      success:res=> {

        console.log('h01---------'+res.windowHeight)

        this.globalData.height_01 = res.windowHeight;
      }
    })



    that.getunreadcount();

  },
  // end onLanch
  // 全局变量
  globalData: {
    userInfo: "",
    js_code: "",
    openid: "",
    session_key: "",
    access_token: '',
    appid: "wxbc768401ce9c467a", //used to get the session key,see function getSessionkeyAndOpenId
    AppSecret: "e46cee4a45b5d44b0076326cf032cf67",
    sdkAppID: 1400144378,
    accountType: 36862,
    accountMode: 0, //帐号模式，0-表示独立模式，1-表示托管模式
    phoneNumber: "",
    admin: "admin",
    identifier: "",
    sentTo: "17722656615",
    adminSig: ``,
    userSig: "",
    FaceUrl: '',
    companyName: '',
    formId: '',

    navHeight:0,
    perfectInformat:true,
    height_01:''

  },
  // 结束全局变量的定义
  addListener: function(callback) {
    this.callback = callback;
  },
  setChangedData: function(data) {
    this.data = data;
    if (this.callback != null) {
      this.callback(data);
    }
  },
  // end setChangedData

 refreshSessionkeyAndOpenId: function() {
    var that = this;
    console.log("refresh session key and openID every 7000 seconds");
    getSessionkeyAndOpenId(that);
  },
//end refreshSessionkeyAndOpenId
  refreshAccessToken: function() {
    var that = this;
    console.log("refresh access token every 7000 seconds");
    getAccessToken(that);
  },
//end refreshAccessToken
  refreshjs_code: function() {
    var that = this;
    console.log("refresh js_code every 250 seconds");
    var js = that.globalData.js_code;
    console.log("the that.globalData.js_code is ", js);
    wx.login({
      success: function (res) {
        if (res.code) {
          console.log("refresh the js_code successfully,it's value is " + res.code);
          that.globalData.js_code = res.code;
          console.log("globalData.js_code is " + that.globalData.js_code);
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    });
  },
  //end refreshjs_code
  getNewVersion(){
    if (wx.canIUse('getUpdateManager')) {
      console.log("get the new version!")
      const updateManager = wx.getUpdateManager()
      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          updateManager.onUpdateReady(function () {
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function (res) {
                if (res.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                  updateManager.applyUpdate()
                }
              }
            })
          })
          updateManager.onUpdateFailed(function () {
            // 新的版本下载失败
            wx.showModal({
              title: '已经有新版本了哟~',
              content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
            })
          })
        }
      })
    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },

     //判断是否完善信息
     perfectInformation(){
      let that = this;
      console.log('执行')



      setTimeout(function () { 

        if (wx.getStorageSync('userType') != "1"){
          wx.request({
            url: util.api + "/iim/im/viewUser",
            data: { id: wx.getStorageSync('userId') },
            success: function (res) {
              var tmpsig = res.data;
              if (tmpsig.success) {
                console.log(tmpsig.body.data.hasOwnProperty('companyName'))

                if (!tmpsig.body.data.hasOwnProperty('companyName')) {
                  wx.showModal({
                    title: '提示',
                    content: '您的信息未完善，是否进入',
                    confirmText: "进入",
                    // cancelText: "取消订单",
                    success: function (res) {
                      if (res.confirm) {

                        console.log('用户点击主操作')

                        wx.navigateTo({
                          url: '/pages/register/register',
                        })
                        that.globalData.perfectInformat = true

                      } else {

                        that.globalData.perfectInformat = true
                        console.log('用户点击辅助操作')
                      }
                    }
                  });
                }

              }
            },
            fail: function (resp) {
              console.log("getUserSigByTelephone failed,the response is %o", resp)
              return false;
            }
          })
        } 


      
         
     
      
      }, 5*60000);




},
getunreadcount(){
  var that=this;
  // console.log('2秒test')
  setTimeout(function () {
    if (wx.getStorageSync('loginName')){
      wx.request({
        url: util.api + "/iim/im/unreadCount",
        data: {
          loginName: wx.getStorageSync('loginName'),
        },
        success: function (res) {
          var tmpsig = res.data;

          console.log("the return of getunreadcount is:" + tmpsig);
          console.log(tmpsig)

          if (tmpsig.body.data > 0) {
            wx.setTabBarBadge({
              index: 1,
              text: tmpsig.body.data + ""
            })
          } else {
            wx.removeTabBarBadge({
              index: 1
            })
          }


          if (tmpsig.body.userexist=="0"){

            //处理账号同步问题
            if (wx.getStorageSync('loginName') != wx.getStorageSync('isRegistered') && wx.getStorageSync('isRegistered') && wx.getStorageSync('loginName')){
              wx.setStorageSync('loginName', wx.getStorageSync('isRegistered'));
              wx.setStorageSync('userType', "1");
              that.getunreadcount();
            }//账号和手机相当 但是后台不存在
            else{
               //清除缓存
              wx.clearStorage();
              if (getCurrentPages().length != 0) {
                //刷新当前页面的数据
                that.onLoad()
              }

            }

          }else{
              //存在 就正常流程
            that.getunreadcount();
          }

         
         
        }

      });
    }else{
      wx.clearStorage();
      if (getCurrentPages().length != 0) {
        //刷新当前页面的数据
        getCurrentPages()[getCurrentPages().length - 1].onLoad()
      }
      that.getunreadcount();
    }
    

   
  }, 2000);

},

//判断是拨打电话
  phone(id,type){

    let that = this;
    console.log('执行')
    // setTimeout(function () {
      
    wx.request({
      url: util.api+"/iim/im/chatTips",
      data: {
        id:id,
        type:type
        },
        success: function(res) {
          var tmpsig = res.data;
          console.log("the return of getUserSigByTelephone is:" + tmpsig);

          console.log(tmpsig)
  
          if(!tmpsig.success){
           
          }else{
            wx.showModal({
              title: '提示',
              content: '您的咨询的'+tmpsig.body.name+'未回复,是否拨打电话',
              confirmText: "拨打",
              cancelText: "取消",
              success: function (res) {
                if (res.confirm) {
    
                        console.log('用户点击主操作')
                        wx.makePhoneCall({
                          phoneNumber: tmpsig.body.data // 仅为示例，并非真实的电话号码
                        })

                      } else {
                        console.log('用户点击辅助操作')
                      }
                      }
                    });
         

          }
        },
        fail: function(resp) {
          console.log("getUserSigByTelephone failed,the response is %o", resp)
          return false;
        },
      })


      
            // }, 60000);
        },


  //end getNewVersion
  isPhoneNumber(){ //判断是否跳过获取用户手机号
    let that = this;
    wx.request({
      url: util.api + '/sys/dict/listData?type=randomphone',
      success(res) {
        if (res.data.length > 0){
          let RandomPhoneNumber = '1' + (Math.floor(Math.random() * 9000000000) + 1000000000); //随机生成手机号
          wx.request({
            // url: "https://www.cdlpkj.cn/school/a/iim/im/onLogin",
            url: util.api + "/iim/im/decryptPhonetest",
            data: {
              token: wx.getStorageSync('token'),
              encryptedData: RandomPhoneNumber,
            },
            success: function (res) {
              var tmpsig = res.data;
              if (tmpsig.success) {
                wx.showToast({
                  title: tmpsig.msg,
                  duration: 2000
                });
                wx.setStorageSync('isRegistered', RandomPhoneNumber);
              }
            },

            fail: function (resp) {

              wx.showToast({
                title: '请联系管理人员',
                duration: 2000
              });
              console.log("getUserSigByTelephone failed,the response is %o", resp)
              return false;
            },
            complete: function (res) {
              // console.log("the return of consultantRegister complete is:" + res.data);
              // console.log(res);
            } //请求完成后执行的函数
          })
          
        }
      }
    })
  }
})
// end APP

//user define function

// 通过js_code发送request获取session_key和openid
function getSessionkeyAndOpenId(that) {
  // 请求官方接口，获取openid和session_key
  // wx.request({
  //   url: "https://www.xuezhou.xyz/getOpenIDAndSessionKey",
  //   data: {
  //     js_code: that.globalData.js_code,
  //   },
  //   success: function(res) {
  //     console.log("wx.request execute successfully!", res)
  //     that.globalData.openid = res.data.openid;
  //     that.globalData.session_key = res.data.session_key;
  //     console.log("the openid is %o", that.globalData.openid);
  //     console.log("the session_key is %o", that.globalData.session_key);

  //   },
  //   fail: function(res) {
  //     console.log("wx.request execute failed!", res)
  //   }
  // })
  // 结束wx.request
}
// end getSessionkeyAndOpenId
function getAccessToken(that) {
  // 获取access_token
  // wx.request({
  //   url: 'https://www.xuezhou.xyz/getAccessToken',
  //   method: "GET",
  //   success: function(res) {
  //     console.log(res, "res")
  //     console.log("the access_token is", res.data.access_token, )
  //     that.globalData.access_token = res.data.access_token;
  //   }
  // })
  // end wx.request
}
// end getAccessToken




